/** @format */
import { services, checkParams, noCheckUser, registeInfos } from '../../decorator/common'
import { resultsModel } from '../../sdk'
import {
  CommonUserService,
  CommonBaseService,
  CommonStatService,
} from '../../service/common'
import { DRAW_STATUS, STAT_TYPE } from '../../constants'
import { CODE_TYPES } from '../../errorCode'
import { noCheckActivityInfo } from '../../decorator/common/noCheckUser'

export default class LoginController {
  /**
   *  登录接口, 初始化/更新用户信息
   */
  @checkParams(['source', 'shop_id'])
  @noCheckUser
  @noCheckActivityInfo
  @services([CommonUserService])
  async register(
    context: IContext<IParams>,
    {}: IControllerInfos,
    [commonUserService]: [CommonUserService]
  ) {
    const { source, shop_id } = context.data
    const commonUserDoLoginResult1 = await commonUserService.registerInfo(source, shop_id)
    return resultsModel.success(commonUserDoLoginResult1)
  }

  @checkParams(['activityId', 'envType?'])
  @noCheckUser
  @noCheckActivityInfo
  @services([CommonBaseService])
  async getEnvConfig(context: IContext<IParams>, {}: IControllerInfos, [commonBaseService]: [CommonBaseService]) {
    const commonBaseGetBaseInfoResult1: any = await commonBaseService.getEnvConfig()
    return resultsModel.success({
      ...commonBaseGetBaseInfoResult1
    })
  }

  @checkParams(['env'])
  @noCheckUser
  @noCheckActivityInfo
  @services([CommonBaseService])
  async getUrl(context: IContext<IParams>, {}: IControllerInfos, [commonBaseService]: [CommonBaseService]) {
    const {env} = context.data
    const commonBaseGetBaseInfoResult1: any = await commonBaseService.getCommonUrl(env)
    return resultsModel.success({
      ...commonBaseGetBaseInfoResult1
    })
  }

  @checkParams(['shopId','itemId','source?'])
  @noCheckUser
  @noCheckActivityInfo
  @services([])
  async domark(context: IContext<IParams>, {}: IControllerInfos, []: []) {
    const {shopId,itemId,source = ''} = context.data
    const cloud = context.cloud;
    const { openId } = context
    try {
      //查询数据库商家的session信息
      const result = await cloud.db.collection('c_key').find({
          name: 'session',
      });
      if (result && result.length > 0) {
          //查询到相关session
          const shopSession = result[0][shopId]
          if (shopSession) {
              //查询到相关session，则调用打标接口
              const apiResult = await context.cloud.topApi.invoke({
                  api: 'taobao.opentrade.special.users.mark',
                  data: {
                      'hit': true,
                      'open_user_ids': openId,
                      'item_id': itemId,
                      'sku_id': "0",
                      'status': 'MARK',
                      'limit_num': 1,
                      'session': shopSession
                  },
              });
              if (apiResult && apiResult.result && apiResult.result > 0) {
                  //打标成功，则先将打标信息存入记录表
                  try {
                      await cloud.db.collection('mark_record').insertOne({
                          openId,
                          shopId,
                          itemId,
                          source,
                          createTime: Date.now(),
                      });
                  } catch (error2) {
                      console.log('新增失败', error2)
                  }
                  //打标成功
                  return { success: true, data: apiResult, message: "请求成功" };
              }
          }
          return { success: false, data: "", message: "系统错误" }
      }
      return { success: false, data: "", message: "系统错误" }
  } catch (error) {
      return { success: false, data: error, message: "系统错误" }
  }
  }


  @checkParams(['shopId','itemId','openId','source?'])
  @noCheckUser
  @noCheckActivityInfo
  @services([])
  async domarkByOpenId(context: IContext<IParams>, {}: IControllerInfos, []: []) {
    const {shopId,itemId,openId,source = ''} = context.data
    const cloud = context.cloud;
    try {
      //查询数据库商家的session信息
      const result = await cloud.db.collection('c_key').find({
          name: 'session',
      });
      if (result && result.length > 0) {
          //查询到相关session
          const shopSession = result[0][shopId]
          if (shopSession) {
              //查询到相关session，则调用打标接口
              const apiResult = await context.cloud.topApi.invoke({
                  api: 'taobao.opentrade.special.users.mark',
                  data: {
                      'hit': true,
                      'open_user_ids': openId,
                      'item_id': itemId,
                      'sku_id': "0",
                      'status': 'MARK',
                      'limit_num': 1,
                      'session': shopSession
                  },
              });
              if (apiResult && apiResult.result && apiResult.result > 0) {
                  //打标成功，则先将打标信息存入记录表
                  try {
                      await cloud.db.collection('mark_record').insertOne({
                          openId,
                          shopId,
                          itemId,
                          source,
                          createTime: Date.now(),
                      });
                  } catch (error2) {
                      console.log('新增失败', error2)
                  }
                  //打标成功
                  return { success: true, data: apiResult, message: "请求成功" };
              }
          }
          return { success: false, data: "", message: "系统错误" }
      }
      return { success: false, data: "", message: "系统错误" }
  } catch (error) {
      return { success: false, data: error, message: "系统错误" }
  }
  }


  @checkParams(['source'])
  @noCheckUser
  @noCheckActivityInfo
  @services([CommonStatService])
  async exportStats(context: IContext<IParams>, {}: IControllerInfos, [commonStatService]: [CommonStatService]) {
    const {source} = context.data
    const commonBaseGetBaseInfoResult1: any = await commonStatService.exportMarkStats(source)
    return resultsModel.success({
      ...commonBaseGetBaseInfoResult1
    })
  }
  
}
